package com.broada.apm.utils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂
 * @author jianfei.xu
 * @date   2016年9月7日
 */
public class APMThreadFactory implements ThreadFactory {
	
    private final AtomicInteger threadNumber = new AtomicInteger(0);

    private final boolean daemon;
    
    private int priority;
    
    private String threadName;

    public APMThreadFactory() {
        this("APM", false, Thread.NORM_PRIORITY);
    }

    public APMThreadFactory(String threadName) {
        this(threadName, false, Thread.NORM_PRIORITY);
    }

    public APMThreadFactory(String threadName, boolean daemon) {
    	this(threadName, daemon, Thread.NORM_PRIORITY);
    }
    
    public APMThreadFactory(String threadName, boolean daemon, int priority) {
        if (threadName == null) {
            throw new NullPointerException("threadName");
        }
        
        this.threadName = threadName;
        this.daemon = daemon;
        this.priority = priority;
    }

    @Override
    public Thread newThread(Runnable job) {
        String newThreadName = createThreadName();
        Thread thread = new Thread(job, newThreadName);
        thread.setPriority(priority);
        if (daemon) {
            thread.setDaemon(true);
        }
        return thread;
    }

    private String createThreadName() {
        StringBuilder buffer = new StringBuilder(threadName);
        buffer.append("-");
        buffer.append(threadNumber.getAndIncrement());
        return buffer.toString();
    }

    public static ThreadFactory createThreadFactory(String threadName) {
        return new APMThreadFactory(threadName, false);
    }
    
    public static ThreadFactory createThreadFactory(String threadName, int priority) {
        return new APMThreadFactory(threadName, false, priority);
    }

    public static ThreadFactory createThreadFactory(String threadName, boolean daemon) {
        return new APMThreadFactory(threadName, daemon);
    }
    
    public static ThreadFactory createThreadFactory(String threadName, boolean daemon, int priority) {
        return new APMThreadFactory(threadName, daemon, priority);
    }

}
